<template>
  <div class="app-container">
    <el-form v-show="showSearch" ref="queryRef" :model="queryParams" :inline="true" label-width="68px">
      <el-form-item label="订单号" prop="orderNo">
        <el-input v-model="queryParams.orderNo" placeholder="请输入订单号" clearable style="width: 200px" @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="订单状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="订单状态" clearable style="width: 200px">
          <el-option v-for="dict in statusOptions" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="支付方式" prop="payType">
        <el-select v-model="queryParams.payType" placeholder="支付方式" clearable style="width: 200px">
          <el-option v-for="dict in payTypeOptions" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button v-hasPermi="['order:order:remove']" type="danger" plain icon="Delete" :disabled="multiple" @click="() => handleDelete()"
          >删除</el-button
        >
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @query-table="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="orderList" style="width: 100%" @selection-change="handleSelectionChange">
      <el-table-column type="expand">
        <template #default="props">
          <div v-for="(detail, index) in props.row.orderDetail" :key="index">
            <el-descriptions :column="3" border>
              <el-descriptions-item label="商品名称">{{ detail.productName }}</el-descriptions-item>
              <el-descriptions-item label="商品单价">￥{{ detail.price }}</el-descriptions-item>
              <el-descriptions-item label="购买数量">{{ detail.quantity }}</el-descriptions-item>
              <el-descriptions-item label="货道编号">{{ detail.channelNo }}</el-descriptions-item>
              <el-descriptions-item label="货道位置">{{ detail.channelPosition }}</el-descriptions-item>
              <el-descriptions-item label="小计">￥{{ detail.subtotal }}</el-descriptions-item>
            </el-descriptions>
            <el-image
              v-if="detail.productImage"
              style="width: 100px; height: 100px; margin-top: 10px"
              :src="detail.productImage"
              :preview-src-list="[detail.productImage]"
              fit="cover"
            />
          </div>
        </template>
      </el-table-column>
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="订单号" align="center" prop="orderNo" min-width="180" />
      <el-table-column label="订单金额" align="center" width="120">
        <template #default="scope">
          <div>总金额：{{ scope.row.totalAmount || '0.00' }}</div>
          <div v-if="scope.row.discountAmount && scope.row.discountAmount !== '0.00'">优惠：{{ scope.row.discountAmount }}</div>
          <div>实付：{{ scope.row.actualAmount || '0.00' }}</div>
        </template>
      </el-table-column>
      <el-table-column label="优惠券" align="center" width="150">
        <template #default="scope">
          <div v-if="scope.row.orderCoupon && scope.row.orderCoupon.couponName">
            <el-tag type="success">{{ scope.row.orderCoupon.couponName }}</el-tag>
            <div class="mt-1 text-gray-500 text-sm">
              {{ scope.row.orderCoupon.couponCode || '-' }}
            </div>
          </div>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="支付方式" align="center" width="100">
        <template #default="scope">
          <el-tag :type="getPayTypeClass(scope.row.payType)">
            {{ getPayTypeLabel(scope.row.payType) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="订单状态" align="center" width="100">
        <template #default="scope">
          <el-tag :type="getOrderStatusType(scope.row.status)">
            {{ getOrderStatusName(scope.row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="时间信息" align="center" min-width="280">
        <template #default="scope">
          <div class="time-info">
            <div>创建：{{ parseTime(scope.row.createTime) || '-' }}</div>
            <div v-if="scope.row.payTime">支付：{{ parseTime(scope.row.payTime) }}</div>
            <div v-if="scope.row.completeTime">完成：{{ parseTime(scope.row.completeTime) }}</div>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="120">
        <template #default="scope">
          <div class="operation-buttons">
            <el-tooltip content="查看详情" placement="top">
              <el-button v-hasPermi="['order:order:query']" link type="primary" :icon="View" @click="handleView(scope.row)" />
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button v-hasPermi="['order:order:remove']" link type="danger" :icon="Delete" @click="handleDelete(scope.row)" />
            </el-tooltip>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" :total="total" @pagination="getList" />

    <!-- 添加或修改订单对话框 -->
    <el-dialog v-model="open" :title="title" width="780px" append-to-body>
      <div v-if="title === '查看订单'">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="订单编号" :span="2">{{ form.orderNo || '-' }}</el-descriptions-item>
          <el-descriptions-item label="外部订单号" :span="2">{{ form.outTradeNo || '暂无' }}</el-descriptions-item>

          <!-- 金额信息 -->
          <el-descriptions-item label="总金额">
            <el-tag type="success">￥{{ form.totalAmount || '0.00' }}</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="实付金额">
            <el-tag type="warning">￥{{ form.actualAmount || '0.00' }}</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="优惠金额">
            <el-tag type="info">￥{{ form.discountAmount || '0.00' }}</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="支付方式">
            <el-tag :type="getPayTypeClass(form.payType)">
              {{ getPayTypeLabel(form.payType) }}
            </el-tag>
          </el-descriptions-item>

          <!-- 状态信息 -->
          <el-descriptions-item label="订单状态">
            <el-tag :type="getOrderStatusType(form.status)">
              {{ getOrderStatusName(form.status) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="用户ID">{{ form.userId || '-' }}</el-descriptions-item>

          <!-- 时间信息 -->
          <el-descriptions-item label="创建时间">{{ parseTime(form.createTime) || '-' }}</el-descriptions-item>
          <el-descriptions-item label="支付时间">{{ parseTime(form.payTime) || '未支付' }}</el-descriptions-item>
          <el-descriptions-item label="完成时间">{{ parseTime(form.completeTime) || '未完成' }}</el-descriptions-item>
          <el-descriptions-item label="取消时间">{{ parseTime(form.cancelTime) || '未取消' }}</el-descriptions-item>

          <!-- 备注信息 -->
          <el-descriptions-item label="备注信息" :span="2">{{ form.remark || '暂无备注' }}</el-descriptions-item>
          <el-descriptions-item label="取消原因" :span="2">{{ form.cancelReason || '暂无' }}</el-descriptions-item>
        </el-descriptions>

        <!-- 订单详情信息 -->
        <div v-if="form.orderDetail && form.orderDetail.length > 0" class="detail-section">
          <div class="section-title">商品信息</div>
          <div v-for="(detail, index) in form.orderDetail" :key="index" class="mb-4">
            <el-descriptions :column="2" border>
              <el-descriptions-item label="商品名称">{{ detail.productName || '-' }}</el-descriptions-item>
              <el-descriptions-item label="商品ID">{{ detail.productId || '-' }}</el-descriptions-item>
              <el-descriptions-item label="单价">￥{{ detail.price || '0.00' }}</el-descriptions-item>
              <el-descriptions-item label="数量">{{ detail.quantity || '0' }}</el-descriptions-item>
              <el-descriptions-item label="小计">￥{{ detail.subtotal || '0.00' }}</el-descriptions-item>
              <el-descriptions-item label="状态">
                <el-tag :type="detail.status === 1 ? 'success' : 'info'">
                  {{ detail.status === 1 ? '正常' : '异常' }}
                </el-tag>
              </el-descriptions-item>
              <el-descriptions-item label="货道编号">{{ detail.channelNo || '-' }}</el-descriptions-item>
              <el-descriptions-item label="货道位置">{{ detail.channelPosition || '-' }}</el-descriptions-item>
            </el-descriptions>

            <div v-if="detail.productImage" class="product-image">
              <div class="image-title">商品图片</div>
              <el-image
                :src="detail.productImage"
                :preview-src-list="[detail.productImage]"
                fit="cover"
                style="width: 120px; height: 120px; border-radius: 4px"
              />
            </div>
          </div>
        </div>

        <!-- 优惠券信息 -->
        <div v-if="form.orderCoupon" class="detail-section">
          <div class="section-title">优惠券信息</div>
          <el-descriptions :column="2" border>
            <el-descriptions-item label="优惠券名称">{{ form.orderCoupon.couponName || '-' }}</el-descriptions-item>
            <el-descriptions-item label="优惠券编码">{{ form.orderCoupon.couponCode || '-' }}</el-descriptions-item>
            <el-descriptions-item label="优惠金额">￥{{ form.orderCoupon.discountAmount || '0.00' }}</el-descriptions-item>
            <el-descriptions-item label="优惠券类型">
              <el-tag :type="form.orderCoupon.couponType === 1 ? 'success' : 'warning'">
                {{ form.orderCoupon.couponType === 1 ? '满减券' : '折扣券' }}
              </el-tag>
            </el-descriptions-item>
          </el-descriptions>
        </div>
      </div>

      <el-form v-else ref="orderRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="订单号" prop="orderNo">
          <el-input v-model="form.orderNo" placeholder="请输入订单号" />
        </el-form-item>
        <el-form-item label="总金额" prop="totalAmount">
          <el-input-number v-model="form.totalAmount" :precision="2" :step="0.1" :min="0" placeholder="请输入总金额" style="width: 100%" />
        </el-form-item>
        <el-form-item label="实际金额" prop="actualAmount">
          <el-input-number v-model="form.actualAmount" :precision="2" :step="0.1" :min="0" placeholder="请输入实际金额" style="width: 100%" />
        </el-form-item>
        <el-form-item label="折扣金额" prop="discountAmount">
          <el-input-number v-model="form.discountAmount" :precision="2" :step="0.1" :min="0" placeholder="请输入折扣金额" style="width: 100%" />
        </el-form-item>
        <el-form-item label="支付方式" prop="payType">
          <el-select v-model="form.payType" placeholder="请选择支付方式">
            <el-option v-for="dict in payTypeOptions" :key="dict.value" :label="dict.label" :value="dict.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="订单状态" prop="status">
          <el-select v-model="form.status" placeholder="请选择订单状态">
            <el-option v-for="dict in statusOptions" :key="dict.value" :label="dict.label" :value="dict.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入备注" />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <template v-if="title === '查看订单'">
            <el-button @click="cancel">关 闭</el-button>
          </template>
          <template v-else>
            <el-button type="primary" @click="submitForm">确 定</el-button>
            <el-button @click="cancel">取 消</el-button>
          </template>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts" name="Order">
import { listOrder, getOrder, addOrder, updateOrder, delOrder } from '@/api/order/order';
import { OrderQuery, OrderVO, OrderForm } from '@/api/order/order/types';
import type { FormInstance, TagProps } from 'element-plus';
import type { DictDataOption } from '@/types/dict';
import { View, Edit, Delete } from '@element-plus/icons-vue';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

// 定义表单 ref
const orderRef = ref<FormInstance>();
const queryRef = ref<FormInstance>();

const orderList = ref<OrderVO[]>([]);
const open = ref(false);
const loading = ref(false);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref('');

// 支付方式选项
const payTypeOptions = ref<DictDataOption[]>([
  { label: '微信', value: 1, listClass: 'success' },
  { label: '余额', value: 2, listClass: 'primary' },
  { label: '积分', value: 3, listClass: 'warning' },
  { label: '支付宝', value: 4, listClass: 'info' }
]);

// 订单状态选项
const statusOptions = ref<DictDataOption[]>([
  { label: '待支付', value: 0, listClass: 'info' },
  { label: '支付中', value: 1, listClass: 'warning' },
  { label: '支付成功', value: 2, listClass: 'success' },
  { label: '支付失败', value: 3, listClass: 'danger' },
  { label: '已取消', value: 4, listClass: 'danger' },
  { label: '已完成', value: 5, listClass: 'success' }
]);

// 查询参数
const queryParams = ref<OrderQuery>({
  pageNum: 1,
  pageSize: 10,
  orderNo: undefined,
  status: undefined,
  payType: undefined
});

const rules = ref({
  orderNo: [{ required: true, message: '订单号不能为空', trigger: 'blur' }],
  totalAmount: [{ required: true, message: '总金额不能为空', trigger: 'blur' }],
  actualAmount: [{ required: true, message: '实际金额不能为空', trigger: 'blur' }],
  status: [{ required: true, message: '订单状态不能为空', trigger: 'change' }]
});

const form = ref<OrderForm>({});

/** 查询订单列表 */
function getList() {
  loading.value = true;
  listOrder(queryParams.value).then((response) => {
    console.log(response);
    orderList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

/** 取消按钮 */
function cancel() {
  open.value = false;
  reset();
}

/** 表单重置 */
function reset() {
  form.value = {
    orderNo: '',
    totalAmount: 0,
    actualAmount: 0,
    discountAmount: 0,
    payType: undefined,
    status: undefined,
    remark: ''
  };
  orderRef.value?.resetFields();
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  queryRef.value?.resetFields();
  handleQuery();
}

/** 多选框选中数据 */
function handleSelectionChange(selection: OrderVO[]) {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length !== 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = '添加订单';
}

/** 处理金额字段类型转换 */
function formatAmount(value: string | number | null | undefined): number {
  if (value === null || value === undefined) return 0;
  const num = typeof value === 'string' ? parseFloat(value) : value;
  return Number.isNaN(num) ? 0 : Number(num.toFixed(2));
}

/** 修改按钮操作 */
function handleUpdate(row?: OrderVO) {
  reset();
  const id = row?.id || ids.value[0];
  getOrder(id).then((response) => {
    const data = response.data;
    // 处理订单详情中的金额
    if (data.orderDetail) {
      data.orderDetail = {
        ...data.orderDetail,
        price: formatAmount(data.orderDetail.price),
        subtotal: formatAmount(data.orderDetail.subtotal)
      };
    }

    form.value = {
      ...data,
      totalAmount: formatAmount(data.totalAmount),
      actualAmount: formatAmount(data.actualAmount),
      discountAmount: formatAmount(data.discountAmount)
    };
    open.value = true;
    title.value = '修改订单';
  });
}

/** 提交按钮 */
function submitForm() {
  orderRef.value?.validate((valid: boolean) => {
    if (valid) {
      if (form.value.id) {
        updateOrder(form.value).then((response) => {
          proxy?.$modal.msgSuccess('修改成功');
          open.value = false;
          getList();
        });
      } else {
        addOrder(form.value).then((response) => {
          proxy?.$modal.msgSuccess('新增成功');
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row?: OrderVO) {
  const orderIds = row?.id || ids.value;
  proxy?.$modal.confirm('是否确认删除订单编号为"' + orderIds + '"的数据项？').then(() => {
    delOrder(orderIds).then(() => {
      getList();
      proxy?.$modal.msgSuccess('删除成功');
    });
  });
}

/** 查看按钮操作 */
function handleView(row: OrderVO) {
  reset();
  const id = row.id;
  getOrder(id).then((response) => {
    const data = response.data;
    // 处理订单详情中的金额
    if (data.orderDetail) {
      data.orderDetail = {
        ...data.orderDetail,
        price: formatAmount(data.orderDetail.price),
        subtotal: formatAmount(data.orderDetail.subtotal)
      };
    }

    form.value = {
      ...data,
      totalAmount: formatAmount(data.totalAmount),
      actualAmount: formatAmount(data.actualAmount),
      discountAmount: formatAmount(data.discountAmount)
    };
    open.value = true;
    title.value = '查看订单';
  });
}

/** 获取支付方式标签类型 */
const getPayTypeClass = (type: number | null | undefined): TagProps['type'] => {
  if (type === null || type === undefined) return 'info';
  const payTypeMap: Record<number, TagProps['type']> = {
    1: 'success', // 微信
    2: 'primary', // 余额
    3: 'warning', // 积分
    4: 'info' // 支付宝
  };
  return payTypeMap[type] || 'info';
};

/** 获取支付方式标签文本 */
const getPayTypeLabel = (type: number | null | undefined): string => {
  if (type === null || type === undefined) return '未知方式';
  const payTypeItem = payTypeOptions.value.find((item) => item.value === type);
  return payTypeItem ? payTypeItem.label : '未知方式';
};

/** 获取订单状态类型 */
const getOrderStatusType = (status: number | null | undefined): TagProps['type'] => {
  if (status === null || status === undefined) return 'info';
  switch (status) {
    case 1:
      return 'info'; // 待支付
    case 2:
      return 'warning'; // 已支付
    case 3:
      return 'success'; // 已发货
    case 4:
      return 'danger'; // 已取消
    case 5:
      return 'success'; // 已完成
    case 6:
      return 'danger'; // 已退款
    default:
      return 'info';
  }
};

/** 获取订单状态名称 */
const getOrderStatusName = (status: number | null | undefined): string => {
  if (status === null || status === undefined) return '未知状态';
  switch (status) {
    case 1:
      return '待支付';
    case 2:
      return '已支付';
    case 3:
      return '已发货';
    case 4:
      return '已取消';
    case 5:
      return '已完成';
    case 6:
      return '已退款';
    default:
      return '未知状态';
  }
};

getList();
</script>

<style lang="scss" scoped>
.amount-info {
  display: flex;
  justify-content: space-around;
  align-items: center;
  gap: 8px;
}

.time-info {
  display: flex;
  flex-direction: column;
  gap: 4px;
  font-size: 13px;
}

.time-info div {
  line-height: 1.5;
}

.el-tag + .el-tag {
  margin-left: 8px;
}

.detail-section {
  margin-top: 20px;

  .section-title {
    font-size: 16px;
    font-weight: 600;
    color: #303133;
    margin-bottom: 16px;
    padding-left: 10px;
    border-left: 4px solid var(--el-color-primary);
  }

  & + .detail-section {
    margin-top: 30px;
  }
}

.product-image {
  margin-top: 20px;

  .image-title {
    font-size: 14px;
    color: #606266;
    margin-bottom: 8px;
  }
}

:deep(.el-descriptions) {
  margin-bottom: 20px;

  .el-descriptions__header {
    margin-bottom: 0;
  }

  .el-descriptions__label {
    font-weight: 600;
    color: #606266;
    width: 120px;
  }

  .el-descriptions__content {
    color: #303133;
  }

  .el-tag {
    margin: 0 4px;
  }
}

.dialog-footer {
  padding-top: 20px;
  text-align: right;
}

.operation-buttons {
  display: flex;
  justify-content: center;
  gap: 12px;

  :deep(.el-button) {
    padding: 6px;
    margin: 0;
    border-radius: 4px;

    &:hover {
      transform: scale(1.1);
      transition: transform 0.2s ease;
    }

    .el-icon {
      font-size: 16px;
    }
  }
}

.mt-1 {
  margin-top: 4px;
}

.text-gray-500 {
  color: #6b7280;
}

.text-sm {
  font-size: 12px;
}
</style>
